<template>
  <div>
    <el-container style="height: 100vh;">
      <el-header style="height: 60px; background-color: #0A1F44; display: flex; align-items: center; justify-content: space-between; padding: 0 20px;">
        <!-- 左侧LOGO与标题 -->
        <div class="team-name" style="color: white; font-size: 20px; font-weight: bold; display: flex; align-items: center;">
          <i class="el-icon-s-grid" style="margin-right: 10px;"></i>
          云电监测系统
        </div>

        <!-- 中间导航菜单 -->
        <el-menu
            :default-active="activePath"
            mode="horizontal"
            @select="handleSelect"
            background-color="#0A1F44"
            text-color="#ffffff"
            active-text-color="#ffd04b"
            style="border-bottom: none;"
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <el-menu-item v-if="hasPermission('device:view')" index="/home/deviceadmin">设备管理</el-menu-item>
          <el-menu-item v-if="hasPermission('data:monitor')" index="/home/datamonitor">数据监测</el-menu-item>
          <el-menu-item v-if="hasPermission('data:analyze')" index="/home/analysis">统计分析</el-menu-item>
          <el-menu-item v-if="hasPermission('user:manage')" index="/home/system">系统管理</el-menu-item>
        </el-menu>

        <!-- 右侧用户菜单 -->
        <div style="display: flex; align-items: center;">
          <el-dropdown @command="handleUserCommand">
      <span class="el-dropdown-link" style="color: #fff; display: flex; align-items: center;">
        <el-avatar size="small" icon="el-icon-user-solid"></el-avatar>
        <span style="margin-left: 8px;">用户</span>
        <i class="el-icon-caret-bottom el-icon--right" style="margin-left: 4px;"></i>
      </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile" @click.native="goToUser">个人中心</el-dropdown-item>
              <el-dropdown-item command="logout" divided @click.native="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>

      <el-main>
        <router-view/>
      </el-main>

      <el-footer v-show="Visible" style="text-align: center; font-size: medium; background-color: rgb(10, 31, 68)">
      </el-footer>
    </el-container>
  </div>
</template>

<style scoped>
/* 样式穿透（Vue 2 用 /deep/） */
/deep/ .el-menu-item.is-active {
  position: relative;
  color: #ffd04b !important; /* 强制选中文字颜色 */
}
/deep/ .el-menu-item.is-active::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 3px;
  background-color: #ffd04b;
  border-radius: 3px 3px 0 0;
}

/* 鼠标悬停效果 */
/deep/ .el-menu-item:not(.is-active):hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 菜单项高度与头部对齐 */
/deep/ .el-menu--horizontal .el-menu-item {
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
}

/* 去除底部边框 */
/deep/ .el-menu--horizontal {
  border-bottom: none !important;
}
</style>

<script>
import { api } from "@/api";
import { hasPermission } from "@/utils/permission";

export default {
  name: "HomeView",
  data() {
    return {
      activePath: this.getMatchedPath(), // 初始化时精确匹配路径
      Visible: false,
      scrollThreshold: 100
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    hasPermission,

    // 关键：根据当前路由获取匹配的导航项路径（解决嵌套路由匹配问题）
    getMatchedPath() {
      const { path } = this.$route;
      // 首页特殊处理（/home 或 /home/ 都匹配 /home）
      if (path === '/home' || path === '/home/') return '/home';
      // 匹配子路由（如 /home/deviceadmin/detail → 取到 /home/deviceadmin）
      const navPaths = ['/home/deviceadmin', '/home/datamonitor', '/home/analysis', '/home/system'];
      const matched = navPaths.find(navPath => path.startsWith(navPath));
      return matched || path; // 找不到匹配项则用当前路径
    },

    // 导航项点击处理
    handleSelect(key) {
      // 路由跳转成功后，再更新activePath（确保同步）
      this.$router.push(key).then(() => {
        this.activePath = key; // 路由跳转成功后才更新选中状态
      }).catch(err => {
        console.error('路由跳转失败：', err);
      });
    },

    goToUser() {
      this.$router.push('/home/user').catch(err => {
        console.error('跳转个人中心失败：', err);
      });
    },

    logout() {
      api.user.logout()
          .then(response => {
            if (response.status === 'success') {
              localStorage.removeItem('satoken');
              localStorage.removeItem('userPermissions');
              this.$router.push('/');
              this.$message.success('退出成功');
            }
          })
          .catch(error => {
            this.$message.error('退出失败：' + (error.message || '网络错误'));
          });
    },

    handleScroll() {
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      this.Visible = scrollTop > this.scrollThreshold;
    },

    handleUserCommand(command) {
      console.log("用户菜单命令：", command);
    }
  },

  watch: {
    // 路由变化时，重新计算匹配的导航项路径
    '$route'() {
      this.activePath = this.getMatchedPath();
    }
  }
};
</script>